//
//  ViewController.m
//  PlayerKitDemo
//
//  Created by Z on 15/7/24.
//  Copyright (c) 2015年 Project. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) id playbackTimeObserver;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    AVAsset *asset = [AVURLAsset URLAssetWithURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1_pan" ofType:@"mp3"]] options:nil];
    [self.player setAllowsExternalPlayback:YES];
    AVPlayerItem *avplayerItem = [AVPlayerItem playerItemWithAsset:asset];
    [avplayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [avplayerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    self.playerItem = avplayerItem;
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.player.volume = 1.0f;
}

// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"])
    {
        if ([playerItem status] == AVPlayerStatusReadyToPlay)
        {
            NSLog(@"AVPlayerStatusReadyToPlay");
            CMTime duration = self.playerItem.duration;// 获取视频总长度
            NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            [self.player play];
        }
        else if ([playerItem status] == AVPlayerStatusFailed)
        {
            NSLog(@"AVPlayerStatusFailed");
        }
        else
        {
            
        }
    }
    else if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        /*
         NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
         NSLog(@"Time Interval:%f",timeInterval);
         CMTime duration = self.playerItem.duration;
         CGFloat totalDuration = CMTimeGetSeconds(duration);
         [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
         */
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
